<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends HomeController
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function saveToApp(Request $request)
    {
        try{
            $this->validate($request, [
                'token'  => 'required',
                'apptoken'  => 'required',
                'imagedata'   => 'required'
            ]);

            $apptoken = $request->input('apptoken');
            $imagedata = $request->input('imagedata');
            $imagepath = $request->input('imagepath');

            $destpath = get_app_path($apptoken);

            if(is_dir($destpath)) {
                if(empty($imagepath)) {
                    $imagepath .= '/' . time() . '.png';
                }
                $destpath .= $imagepath;
                file_put_contents($destpath, $imagedata);
                return response()->json(build_result(["filename" => $imagepath]));
            } else {
                return response()->json(build_result('', '51002'));
            }
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }

    // 保存图片到res工程
    public function saveToRes(Request $request)
    {
        try{
            $this->validate($request, [
                'apptoken'  => 'required',
                'imagedata'   => 'required'
            ]);

            $apptoken = $request->input('apptoken');
            $imagedata = $request->input('imagedata');

            // 拼装文件路径
            $imagepath = '/' . date("Ym/d") . '/';
            $imagename = 'img' . $apptoken . time() .'.png';

            if(!is_dir(get_resource_dir() . $imagepath)) {
                mkdir(get_resource_dir() . $imagepath, 0777, true);
            }
            file_put_contents(get_resource_dir() . $imagepath . $imagename, $imagedata);
            return response()->json(build_result(["filename" => env('RES_HOST') . $imagepath . $imagename]));
        } catch(\Exception $e) {
            return response()->json(build_result('', '10001', $e->getMessage()));
        }
    }
}
